package Forms;

import Classes.DateTime;
import Classes.Server;
import java.awt.event.*;
import java.io.*;
import java.net.InetAddress;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.text.DefaultCaret;

public class ServerFrame extends javax.swing.JFrame {
    private static DateTime dt;
    private ArrayList<String> textArea = new ArrayList<String>();
    private int clients;
    private int users;
    private static Server s = null;
    private static ServerFrame sf;
    
    public ServerFrame() {
        initComponents();
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        
        File f = new File("C:" + File.separator + "MEAB Server Logs");
        try {            
            dt = new DateTime();
            dateL.setText(dt.getCurrentDate());
            timeL.setText(dt.getCurrentTime());
            ipaddL.setText(InetAddress.getLocalHost().getHostAddress());
            usersL.setText("");
            clients = 0;
            updateLabel("clients", 0);
            
            if(!f.exists()) {
                f.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();     
        }
        
        ActionListener a = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    dt = new DateTime();
                    timeL.setText(dt.getCurrentTime());
                    dateL.setText(dt.getCurrentDate());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        };
        Timer t = new Timer(1000, a);
        t.start();
    }
  
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        serverArea = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        dateL = new javax.swing.JLabel();
        timeL = new javax.swing.JLabel();
        label1 = new javax.swing.JLabel();
        usersL = new javax.swing.JLabel();
        ipaddL = new javax.swing.JLabel();
        timeL2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MEAB Server");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/banner.jpg"))); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        serverArea.setColumns(20);
        serverArea.setEditable(false);
        serverArea.setFont(new java.awt.Font("Bookman Old Style", 0, 14));
        serverArea.setLineWrap(true);
        serverArea.setRows(5);
        serverArea.setName("serverArea"); // NOI18N
        jScrollPane1.setViewportView(serverArea);

        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator1.setName("jSeparator1"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setText("Server Logs:");
        jLabel4.setName("jLabel4"); // NOI18N

        dateL.setFont(new java.awt.Font("Tahoma", 0, 24));
        dateL.setText("mm/dd/yyyy");
        dateL.setName("dateL"); // NOI18N

        timeL.setFont(new java.awt.Font("Tahoma", 0, 24));
        timeL.setText("hh:mm am/pm");
        timeL.setName("timeL"); // NOI18N

        label1.setFont(new java.awt.Font("Tahoma", 0, 24));
        label1.setText("Users Logged In:");
        label1.setName("label1"); // NOI18N

        usersL.setFont(new java.awt.Font("Tahoma", 0, 24));
        usersL.setText("0");
        usersL.setName("usersL"); // NOI18N

        ipaddL.setFont(new java.awt.Font("Tahoma", 0, 24));
        ipaddL.setText("192.168.192.168");
        ipaddL.setName("ipaddL"); // NOI18N

        timeL2.setFont(new java.awt.Font("Tahoma", 0, 24));
        timeL2.setText("Server IP Address:");
        timeL2.setName("timeL2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 1361, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1341, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dateL)
                        .addGap(95, 95, 95)
                        .addComponent(timeL)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 575, Short.MAX_VALUE)
                        .addComponent(timeL2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ipaddL)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1341, Short.MAX_VALUE)
                    .addComponent(jLabel4))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(label1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(usersL)
                .addContainerGap(1149, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateL)
                    .addComponent(timeL)
                    .addComponent(ipaddL)
                    .addComponent(timeL2))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label1)
                    .addComponent(usersL))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private static void startRegistry() throws RemoteException{
        try {
          Registry registry = LocateRegistry.getRegistry(1099);
          registry.list( );  
            // This call will throw an exception
            // if the registry does not already exist
        }
        catch (RemoteException e) { 
          // No valid registry at that port.
          Registry registry = 
          LocateRegistry.createRegistry(1099);
        }
    }
    
    public void appendTextArea(String text) {
        dt = new DateTime();
        serverArea.append("\n  " + dt.getCurrDate() + " at " + dt.getCurrentTime() + "   >>   " + text);
        DefaultCaret caret = (DefaultCaret)serverArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        saveLogs("\n  " + dt.getCurrDate() + " at " + dt.getCurrentTime() + "   >>   " + text);
    }
    
    public void updateLabel(String name, int num) {
        if(name.equals("users")) {
            usersL.setText(""+num);
        }
    }
    
    public static String getLastLine() {
        String result = "";
        String[] ss = serverArea.getText().split("\\n");
        for(int x = 0; x < ss.length; x++) {
            result = ss[ss.length-1];
        }
        return result;
    }
    
    public int getNum(String name) {
        if(name.equals("clients")) {
            return clients;
        }
        return users;
    }
    
    public static void saveLogs(String a) {
        File f1 = new File("C:" + File.separator + "MEAB Server Logs" + File.separator + dt.getYear());
        if(!f1.exists()) {
            f1.mkdir();
        } else {
            File f2 = new File("C:" + File.separator + "MEAB Server Logs" + File.separator + dt.getYear() + File.separator + dt.getMonth());
            if(!f2.exists()) {
                f2.mkdir();
            } else {
                try {
                    File f3 = new File("C:" + File.separator + "MEAB Server Logs" + File.separator + dt.getYear() + File.separator + dt.getMonth() + File.separator + dt.getDate() + ".txt");
                    if(!f3.exists()) {
                        f3.createNewFile();
                    }
                    FileWriter fw = new FileWriter(f3, true);
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(a);
                    bw.newLine();
                    bw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    sf = new ServerFrame();
                    s = new Server(sf);
                    s.logout("");
                    startRegistry();
                    Naming.rebind("rmi://localhost:1099/meab", s);
                    sf.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel dateL;
    private javax.swing.JLabel ipaddL;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel label1;
    public static javax.swing.JTextArea serverArea;
    private javax.swing.JLabel timeL;
    private javax.swing.JLabel timeL2;
    private javax.swing.JLabel usersL;
    // End of variables declaration//GEN-END:variables
}
